<?php
// teacher_edit_api.php
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

require 'database.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取并验证输入数据
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $subject = isset($_POST['subject']) ? trim($_POST['subject']) : '';
    $work_time = isset($_POST['work_time']) ? trim($_POST['work_time']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $sex = isset($_POST['sex']) ? trim($_POST['sex']) : '';
    $birthday = isset($_POST['birthday']) ? trim($_POST['birthday']) : '';
    $school = isset($_POST['school']) ? trim($_POST['school']) : '';
    $here_work_time = isset($_POST['here_work_time']) ? trim($_POST['here_work_time']) : '';
    $grade = isset($_POST['grade']) ? trim($_POST['grade']) : '';
    $major = isset($_POST['major']) ? trim($_POST['major']) : '';
    $educational = isset($_POST['educational']) ? trim($_POST['educational']) : '';
    $qualifications = isset($_POST['qualifications']) ? trim($_POST['qualifications']) : '';
    $qualifications_time = isset($_POST['qualifications_time']) ? trim($_POST['qualifications_time']) : '';
    $master_level = isset($_POST['master_level']) ? trim($_POST['master_level']) : '';

    // 验证ID是否存在
    $stmt = $pdo->prepare('SELECT COUNT(*) FROM teachers WHERE id = ?');
    $stmt->execute([$id]);
    if ($stmt->fetchColumn() === 0) {
        die('教师信息不存在');
    }

    try {
        // 更新数据库记录
        $stmt = $pdo->prepare(
            'UPDATE teachers SET 
                name = ?,
                subject = ?,
                work_time = ?,
                phone = ?,
                sex = ?,
                birthday = ?,
                school = ?,
                here_work_time = ?,
                grade = ?,
                major = ?,
                educational = ?,
                qualifications = ?,
                qualifications_time = ?,
                master_level = ?
            WHERE id = ?'
        );

        $stmt->execute([
            $name,
            $subject,
            $work_time,
            $phone,
            $sex,
            $birthday,
            $school,
            $here_work_time,
            $grade,
            $major,
            $educational,
            $qualifications,
            $qualifications_time,
            $master_level,
            $id
        ]);

        // 重定向到教师列表页面
        header('Location: teachers.php');
        exit();
    } catch (PDOException $e) {
        die('数据库错误：' . $e->getMessage());
    }
} else {
    die('非法请求');
}